<template>
  <div class="custom-select">
    <!-- 输入框，用于显示已选值和触发下拉框显示 -->
    <u-input
      v-model="selectedValue"
      readonly
      border
      :disabled="customerForm.customerDisabled"
      @click="showDropdown = !showDropdown"
      placeholder="请选择"
    />
    <!-- 下拉框，当 showDropdown 为 true 时显示 -->
    <div v-if="showDropdown" class="dropdown">
      <!-- 搜索框，用于过滤选项 -->
      <div style="padding: 0 16rpx">
        <u-input
          v-model="searchKeyword"
          @input="filterOptions"
          placeholder="搜索..."
          clearable
          @clear="handleClear"
        />
      </div>
      <!-- 虚拟滚动容器 -->
      <div class="virtual-scroll" ref="scrollContainer" @scroll="handleScroll">
        <div class="options-container" :style="{ height: totalHeight + 'px' }">
          <div
            v-for="item in visibleOptions"
            :key="item.bcId"
            :style="{ top: item.top + 'px' }"
            class="option text-ellipsis"
            @click="selectOption(item)"
          >
            {{ item.bcName }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "CustomSelect",
  props: {
    options: {
      type: Array,
      required: true,
    },
    customerForm: {
      type: Object,
      default: {
        customer_id: "", // 初始值为空字符串
        customerDisabled: false,
      },
    },
  },
  data() {
    return {
      showDropdown: false,
      searchKeyword: "",
      selectedValue: "",
      visibleOptions: [],
      itemHeight: 30, // 每个选项的高度
      visibleCount: 10, // 可视区域显示的选项数量
      scrollTop: 0,
    };
  },
  computed: {
    filteredOptions() {
      if (!this.searchKeyword) {
        return this.options;
      }
      return this.options.filter((item) =>
        item.bcName.includes(this.searchKeyword)
      );
    },
    totalHeight() {
      return this.filteredOptions.length * this.itemHeight;
    },
  },
  watch: {
    // customerForm: {
    //   handler(newVal, oldVal) {
    //     console.log('customerForm changed:', newVal);
    //     if (newVal && newVal.customer_id) {
    //       this.$nextTick(() => {
    //         // this.selectedValue  = newVal.customer_id;
    //       });
    //     }
    //   },
    //   deep: true, // 添加深度监听
    //   immediate: true
    // },
    options(newVal, oldVal) {
      console.log("options 发生变化，新值：", newVal, "旧值：", oldVal);
      if (newVal && this.customerForm.customer_id) {
        let cusData = newVal.find(
          (item) => item.bcId === this.customerForm.customer_id
        );
        this.selectedValue = cusData.bcName;
      }
    },
    filteredOptions() {
      this.updateVisibleOptions();
    },
  },
  mounted() {
    const selectedOption = this.options.find(
      (item) => item.bcId === this.customerId
    );
    if (selectedOption) {
      this.selectedValue = selectedOption.bcName;
    }
    this.updateVisibleOptions();
  },
  methods: {
    updateSelectedValue(val) {
      const selectedOption = this.options.find((item) => item.value === val);
      if (selectedOption) {
        this.selectedValue = selectedOption.label;
      } else {
        this.selectedValue = "";
      }
    },
    filterOptions() {
      this.scrollTop = 0;
      if (this.$refs.scrollContainer) {
        this.$refs.scrollContainer.scrollTop = 0;
      }
    },
    handleScroll() {
      if (this.$refs.scrollContainer) {
        this.scrollTop = this.$refs.scrollContainer.scrollTop;
        this.updateVisibleOptions();
      }
    },
    updateVisibleOptions() {
      const startIndex = Math.floor(this.scrollTop / this.itemHeight);
      const endIndex = startIndex + this.visibleCount + 2; // 多渲染几个选项，避免滚动时空白
      this.visibleOptions = this.filteredOptions
        .slice(startIndex, endIndex)
        .map((item, index) => ({
          ...item,
          top: (startIndex + index) * this.itemHeight,
        }));
    },
    selectOption(item) {
      this.selectedValue = item.bcName;
      this.$emit("input", item.bcId);
      // this.$emit('input', {
      //   bcCode: item.bcCode,
      //   bcId: item.bcId
      // });
      this.showDropdown = false;
    },
    // 处理清除事件
    handleClear() {
      this.scrollTop = 0;
      if (this.$refs.scrollContainer) {
        this.$refs.scrollContainer.scrollTop = 0;
      }
    },
  },
};
</script>

<style scoped>
.text-ellipsis {
  white-space: nowrap; /* 禁止文本换行 */
  overflow: hidden; /* 隐藏溢出的文本 */
  text-overflow: ellipsis; /* 溢出的文本显示为省略号 */
}

.custom-select {
  position: relative;
  /* width: 200px; */
  width: 100%;
}

.custom-select input {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}

.dropdown {
  position: absolute;
  width: 100%;
  border: 1px solid #ccc;
  background-color: white;
  z-index: 1000;
}

/* 新增样式，调整搜索框大小 */
.dropdown input {
  height: 40px; /* 增加高度 */
  font-size: 16px; /* 增大字体大小 */
}

.virtual-scroll {
  height: 300px;
  overflow-y: auto;
}

.options-container {
  position: relative;
}

.option {
  position: absolute;
  width: 100%;
  height: 30px;
  line-height: 30px;
  padding: 0 8px;
  box-sizing: border-box;
  cursor: pointer;
}

.option:hover {
  background-color: #f0f0f0;
}
</style>